﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Speech.Synthesis;
using System.Speech.Recognition;
using System.Collections;
using System.Threading;

namespace HocTiengAnh
{
    public partial class Form1 : Form
    {
        TextBox txtCau;
        TextBox txtNghia;
        DataGridView dataGridView;
        
        //bang luu tru tu dien
        DataTable table;

        //biến lưu gia trị trước va sau khi edit của một cell
        string cellValueBefore;
        int RowSelected;

        //cell user đang làm việc
        DataGridViewCell cellSelected;
        //khoi tao chuc nang nhan dien giong noi
        SpeechRecognitionEngine _recognizer = new SpeechRecognitionEngine();

        //khoi tao may doc chu
        static SpeechSynthesizer _synthesizer = new SpeechSynthesizer();

        string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\tudien.txt";

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.AutoSize = true;
            KhoiTao_recognizer();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (btnNapData.Enabled == false)
            {
                int result = SaoLuuDuLieuTruocKhiThoat();

                if (result == 1 || result == 0)
                {
                    //sao luu du lieu
                    if (result == 1) SaoDulieuDatGridView();
                    //xoa cac thanh phan
                    panel1.Controls.Clear();
                    this.Controls.Clear();
                    _recognizer.Dispose(); //ngừng nhận diện
                }
                else if (result == -1)
                    e.Cancel = true;
            }
            else
            {
                panel1.Controls.Clear();
                this.Controls.Clear();
                _recognizer.Dispose(); //ngừng nhận diện
            }

        }

        int SaoLuuDuLieuTruocKhiThoat()
        {
            DialogResult result = MessageBox.Show("Bạn có muốn save dữ liệu", "Thông báo", MessageBoxButtons.YesNoCancel);
            if (result == DialogResult.Cancel)
                return -1; //huy bo
            else if (result == DialogResult.OK)
                return 1;//luu va thoat
            return 0; //huy bo
        }

        Button btnSave;
        private void btnNapData_Click(object sender, EventArgs e)
        {
            btnNapData.Enabled = false;
            btnNghia.Enabled = true;
            panel1.Controls.Clear();
            panel1.AutoSize = true;
            this.AutoSize = true;
            //
            //button save
            //
            btnSave = new Button();
            btnSave.Text = "Save";
            btnSave.Size = new Size(100, 30);
            btnSave.Location = new Point(220, 300);
            btnSave.Font = new Font("Microsoft Sans Serif", 10);
            btnSave.Enabled = false;
            btnSave.Click += btnSave_Click;
            //
            //lblheader
            //
            Label lblHeader = new Label();
            lblHeader.Location = new Point(200, 3);
            lblHeader.Size = new Size(300, 50);
            lblHeader.Font = new Font("Microsoft Sans Serif", 20);
            lblHeader.Text = "TỪ ĐIỂN CÂU";
            //
            //Add DataGridView
            //
            dataGridView = new DataGridView();
            dataGridView.Location = new Point(5, 70);
            dataGridView.Size = new Size(620, 220);
            dataGridView.AutoSize = false;
            dataGridView.ScrollBars = ScrollBars.Both;
            dataGridView.Font = new Font("Microsoft Sans Serif", 10);
            dataGridView.ColumnHeadersHeight = 30;
            dataGridView.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Sunken;
            dataGridView.CellValidating += dataGridView_CellValidating; //kiem tra sự thay đổi của cell
            dataGridView.CellValueChanged += dataGridView_CellValueChanged; //xảy ra khi giá trị của cell đã thay đổi
            dataGridView.CellBeginEdit += dataGridView_CellBeginEdit;  //lưu giá trị của cell trước khi edit
            dataGridView.AllowUserToDeleteRows = true; //cho phép user delete row
            dataGridView.RowContextMenuStripNeeded += dataGridView_RowContextMenuStripNeeded;

            //
            //Add control to panel
            //
            panel1.Controls.Add(btnSave);
            panel1.Controls.Add(dataGridView);
            panel1.Controls.Add(lblHeader);
            NapDuLieuDataGridView();

        }

        void dataGridView_RowContextMenuStripNeeded(object sender, DataGridViewRowContextMenuStripNeededEventArgs e)
        {
            e.ContextMenuStrip = cmtDataGridView;
            RowSelected = e.RowIndex;
        }

        private void deleteRowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            dataGridView.Rows.RemoveAt(RowSelected);
        }


        private void readToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dataGridView.Rows[RowSelected].Cells[0].Value != null)
                ReadText(dataGridView.Rows[RowSelected].Cells[0].Value.ToString());
        }

        void ReadText(string value)
        {
            _synthesizer.Speak(value);
        }



        void dataGridView_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            cellSelected = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex];
            if (dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
                cellValueBefore = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
        }

        void dataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (btnSave.Enabled == false) btnSave.Enabled = true;
            if (DuLieuDaCo(dataGridView.Rows[e.RowIndex].Cells[0].Value.ToString(), e.RowIndex) == 0)
            {
                MessageBox.Show("Dữ liệu đã có trong danh sách", "Thông báo", MessageBoxButtons.OK);
                if (e.RowIndex == dataGridView.RowCount - 2) dataGridView.Rows.RemoveAt(dataGridView.Rows[e.RowIndex].Index);
                else
                {
                    dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = cellValueBefore;

                }
            };
        }


        void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (string.IsNullOrEmpty(e.FormattedValue.ToString()))
            {
                if (e.RowIndex < dataGridView.RowCount - 1) // neu khong phai la ban ghi cuoi cung (ban ghi tao tu dong)
                {
                    MessageBox.Show("Không được để trống", "Thông báo", MessageBoxButtons.OK);
                    e.Cancel = true; //không cho chuyển sang ô tiếp theo
                }
            }

        }

        int DuLieuDaCo(string e, int rowindex)
        {
            for (int i = 0; i < dataGridView.RowCount && i != rowindex; i++) //i != rowindex ,trừ bản thân bản ghi đang xét
            {
                if (dataGridView.Rows[i].Cells[0].Value != null)
                    if (!string.IsNullOrEmpty(dataGridView.Rows[i].Cells[0].Value.ToString()))
                    {
                        if (e.ToUpper() == dataGridView.Rows[i].Cells[0].Value.ToString().ToUpper()) return 0; //nhap lai
                    }
            }
            return 1;
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            SaoDulieuDatGridView();
            KhoiTao_recognizer();
            btnSave.Enabled = false;
        }

        void SaoDulieuDatGridView()
        {
            StreamWriter writer = new StreamWriter(path);
            foreach (DataGridViewRow row in dataGridView.Rows)
            {
                if (!row.IsNewRow)
                    writer.WriteLine(row.Cells[0].Value + " | " + row.Cells[1].Value);
            }
            writer.Close();
        }
        void NapDuLieuDataGridView()
        {
            dataGridView.DataSource = table;
            dataGridView.Columns[0].Width = 300;
            dataGridView.Columns[1].Width = 300;
            dataGridView.CurrentCell = dataGridView.Rows[dataGridView.RowCount - 1].Cells[0];
        }

        void NapNguPhap()
        {
            //doc du lieu
            using (StreamReader reader = new StreamReader(path))
            {
                table = new DataTable();
                table.Columns.Add("English", typeof(string));
                table.Columns.Add("Tiếng việt", typeof(string));
                GrammarBuilder builder;
                Grammar grammar;
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    if (line.Trim() != "")
                    {
                        int position = line.Trim().LastIndexOf("|");
                        string cau = line.Substring(0, position - 1).Trim();
                        string nghia = line.Substring(position + 1, line.Length - position - 1).Trim();
                        table.Rows.Add(cau, nghia);
                        //them tien to o truoc cau de chuong trinh biet user dang lam viec voi no
                        cau = cau.Insert(0, "Form ");
                        builder = new GrammarBuilder(cau);
                        grammar = new Grammar(builder);
                        _recognizer.LoadGrammar(grammar);
                    }
                }
            }
            //load du lieu vao recognizer


        }

        private void btnNghia_Click(object sender, EventArgs e)
        {
            //chinh lai giao dien
            btnNapData.Enabled = true;
            btnNghia.Enabled = false;
            panel1.Controls.Clear();
            this.AutoSize = false;
            panel1.Size = new Size(panel1.MinimumSize.Width, panel1.MinimumSize.Height);
            this.Size = new Size(this.MinimumSize.Width, this.MinimumSize.Height);
            //
            //lbl header
            //
            Label lblHeader = new Label();
            lblHeader.Location = new Point(170, 3);
            lblHeader.Size = new Size(300, 50);
            lblHeader.Font = new Font("Microsoft Sans Serif", 20);
            lblHeader.Text = "TRA CÂU";
            //
            //textBox cau
            //
            txtCau = new TextBox();
            txtCau.Location = new Point(20, 60);
            txtCau.Font = new Font("Microsoft Sans Serif", 17);
            txtCau.Size = new Size(430, 50);
            txtCau.TextAlign = HorizontalAlignment.Center;
            txtCau.ReadOnly = true;
            //
            //textbox nghia
            //
            txtNghia = new TextBox();
            txtNghia.Location = new Point(20, 120);
            txtNghia.Font = new Font("Microsoft Sans Serif", 10);
            txtNghia.Size = new Size(430, 30);
            txtNghia.TextAlign = HorizontalAlignment.Center;
            txtNghia.ReadOnly = true;

            //Add cac thanh phan to control
            panel1.Controls.Add(lblHeader);
            panel1.Controls.Add(txtCau);
            panel1.Controls.Add(txtNghia);
        }

        void _recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            if (e.Result.Text.ToUpper().Equals("HIDDEN MY FORM"))
                this.WindowState = FormWindowState.Minimized;
            else if (e.Result.Text.ToUpper().Equals("SHOW MY FORM"))
                this.WindowState = FormWindowState.Normal;
            else if (e.Result.Text.ToUpper().Equals("GO TO DATA"))
            {
                btnNapData.PerformClick();
            }
            else if (e.Result.Text.ToUpper().Equals("GO TO TRANSLATE"))
            {
                btnNghia.PerformClick();
            }
            else if(btnNapData.Enabled == true)//khong phai cau lenh he thong
            {
                int rowIndex = 0;

                //khoi tao notification
                NotifyIcon notify = new NotifyIcon();
                notify.BalloonTipIcon = ToolTipIcon.Info;
                notify.Visible = true;
                notify.Icon = SystemIcons.Information; 

                string result = e.Result.Text.Remove(0, ("Form").Length).Trim();
                foreach (DataRow row in table.Rows)
                {
                    string x = row[0].ToString();
                    if (result == x)
                        break;
                    ++rowIndex;
                }
                if (rowIndex >= table.Rows.Count - 1 || result == "FORM")
                {
                    notify.BalloonTipTitle = "Thông báo";
                    notify.BalloonTipText = "Câu bạn vừa nói không có trong từ điển";
                    notify.ShowBalloonTip(300);
                    return;
                } 

                if (btnNghia.Enabled == false)
                {
                    txtCau.Text = result;
                    txtNghia.Text = table.Rows[rowIndex][1].ToString();
                }
                if (this.WindowState == FormWindowState.Minimized)
                {
                    //
                    //Hien thi thong bao he thong khi form hide
                    //
                    notify.BalloonTipTitle = result;
                    notify.BalloonTipText = table.Rows[rowIndex][1].ToString();
                    notify.ShowBalloonTip(3);
                }
            } 
        }

        void KhoiTao_recognizer()
        {
            KhoiTaoLenhWinForm();
            _recognizer.SpeechRecognized += _recognizer_SpeechRecognized;
            _recognizer.SetInputToDefaultAudioDevice();
            _recognizer.RecognizeAsync(RecognizeMode.Multiple);
            //nap du lieu tu dien
            NapNguPhap();
        }

        void KhoiTaoLenhWinForm()
        {
            _recognizer.UnloadAllGrammars();
            Grammar grammar = new Grammar(new GrammarBuilder("Show My Form"));
            _recognizer.LoadGrammar(grammar);
            grammar = new Grammar(new GrammarBuilder("Hidden My Form"));
            _recognizer.LoadGrammar(grammar);
            grammar = new Grammar(new GrammarBuilder("Go to data"));
            _recognizer.LoadGrammar(grammar);
            grammar = new Grammar(new GrammarBuilder("Go to translate"));
            _recognizer.LoadGrammar(grammar);
            grammar = new Grammar(new GrammarBuilder("Form"));
            _recognizer.LoadGrammar(grammar);
        }

        private void getCommandSystemToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //tao form de hien thi thong tin lenh trong chuong trinh
            Form form2 = new Form();
            form2.Text = "Command System";
            form2.AutoSize = true;

            DataGridView datagridview2 = new DataGridView();
            datagridview2.ColumnCount = 2;
            datagridview2.AllowUserToAddRows = false;
            datagridview2.ScrollBars = ScrollBars.Both;
            datagridview2.AllowUserToDeleteRows = false;
            datagridview2.Size = new Size(400, 200);
            datagridview2.ReadOnly = true;
            datagridview2.RowHeadersVisible = false;
            datagridview2.Columns[0].Name = "Command Name";
            datagridview2.Columns[1].Name = "Description";
            datagridview2.Columns[0].Width = 150;
            datagridview2.Columns[1].Width = 250;
            datagridview2.Location = new Point(10, 10);
            datagridview2.Rows.Add("Show my form", "Hiển thị Form khi bị ẩn");
            datagridview2.Rows.Add("Hidden my form", "Ẩn Form");
            datagridview2.Rows.Add("Go to data", "Kích hoạt button Nạp dữ liệu. Để Nhập từ điển");
            datagridview2.Rows.Add("Go to translate", "Kích hoạt button nghĩa của câu để tra câu");
            datagridview2.Rows.Add("Form + \"câu\"", "Để nói với chương trình hẫy tra \"câu\"");

            form2.Controls.Add(datagridview2);
            form2.Show();
           

        }


    }
}
